package edu.sctu;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DataBase {

    public List<User> getUserList(){

        List<User> userList = new ArrayList<User>();

        // 3+1
        try {
            Class.forName("com.mysql.jdbc.Driver");

            Connection connection = null;
            PreparedStatement preparedStatement=null;
            ResultSet resultSet = null;

            String sql = "select * from t_users";

            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/sctu-javaweb-2018?serverTimezone=UTC",
                    "root",
                    "123456"
            );
            preparedStatement=connection.prepareStatement(sql);
            resultSet=preparedStatement.executeQuery();

            while(resultSet.next()){

                int id = resultSet.getInt(1);
                String name = resultSet.getString(2);
                String password = resultSet.getString(3);

                // [封装]在user中
                User user = new User();
                user.setId(id);
                user.setName(name);
                user.setPassword(password);
                userList.add(user);
            }
            // 数据库 -> List
            resultSet.close();
           preparedStatement.close();
            connection.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userList;

    }
}
